package com.happyrecyclingstation.service.impl;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.happyrecyclingstation.constant.MessageConstant;
import com.happyrecyclingstation.dto.AIResumeQuery;
import com.happyrecyclingstation.dto.ResumeDto;
import com.happyrecyclingstation.entity.Delivery;
import com.happyrecyclingstation.entity.Resume;
import com.happyrecyclingstation.mapper.DeliveryMapper;
import com.happyrecyclingstation.mapper.ResumeMapper;
import com.happyrecyclingstation.mapper.UserMapper;
import com.happyrecyclingstation.service.ResumeService;
import com.happyrecyclingstation.utils.CurrentHolder;
import com.happyrecyclingstation.utils.Result;
import com.happyrecyclingstation.vo.HrResumeVO;
import com.happyrecyclingstation.vo.PageResult;
import com.happyrecyclingstation.vo.ResumeVO;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ResumServiceImpl implements ResumeService {
    @Autowired
    private ResumeMapper resumMapper;
    @Autowired
    private DeliveryMapper deliveryMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 保存简历
     * @param resumeDto
     */
    @Override
    public void saveResume(ResumeDto resumeDto) {
        //调用generateResume方法构建Resume对象
        Resume resume = generateResume(resumeDto);
        //查询该用户的简历
        Resume oldResume = resumMapper.getResumeByUserId(CurrentHolder.getCurrentId());
        //判断该用户是否已经保存过简历，如果已经保存过则更新，否则插入
        if (oldResume != null) {
            resume.setId(oldResume.getId());
            resumMapper.updateResume(resume);
        } else {
            resume.setUserId(CurrentHolder.getCurrentId());
            resume.setCreateTime(LocalDateTime.now());
            resumMapper.insertResume(resume);
        }
    }

    /**
     * 根据用户id获取简历
     * @return
     */
    @Override
    public ResumeVO getResumeByUserId() {
        Resume resume = resumMapper.getResumeByUserId(CurrentHolder.getCurrentId());
        if (resume != null){
            //将Resume对象转换成ResumeVo对象
            ResumeVO resumeVo = generateResumeVo(resume);
            return resumeVo;
        }
        ResumeVO resultVo = new ResumeVO();
        resultVo.setEducation(new ArrayList<>());
        resultVo.setWorkExperience(new ArrayList<>());
        resultVo.setProjects(new ArrayList<>());
        resultVo.setSkills(new ArrayList<>());
        return resultVo;
    }

    /**
     * 发送简历
     * @param companyId
     * @param positionId
     */
    @Override
    public Result sendResume(Integer companyId, Integer positionId) {
        // 1.查询当前用户是否有简历
        Resume resume = resumMapper.getResumeByUserId(CurrentHolder.getCurrentId());
        if (resume == null) {
            Result.error(MessageConstant.NO_RESUME);
        }

        // 2.发送简历
        Delivery delivery = new Delivery();
        delivery.setCompanyId(companyId);
        delivery.setPositionId(positionId);
        delivery.setResumeId(resume.getId());
        delivery.setUserId(CurrentHolder.getCurrentId());
        delivery.setStatus((short)1);
        delivery.setIsView((short)0);
        delivery.setCreateTime(LocalDateTime.now());
        delivery.setUpdateTime(LocalDateTime.now());
        deliveryMapper.insert(delivery);
        return Result.success();
    }

    /**
     * 获取简历列表
     */
    @Override
    public Result getResume(Integer posId, Short isView, LocalDateTime createTime, Integer currentPage, Integer pageSize) {
        // 查询当前hr是否关联了企业，如果没有关联则返回错误信息
        Integer companyId = userMapper.isRelated(CurrentHolder.getCurrentId());
        if (companyId == null) {
            return Result.error(MessageConstant.NO_RELATED_COMPANY);
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<HrResumeVO> page = resumMapper.getResume(companyId, posId, isView, createTime);
        return Result.success(new PageResult<HrResumeVO>(page.getTotal(), page.getResult()));
    }

    /**
     * 根据id获取简历
     * @param id
     * @return
     */
    @Override
    public ResumeVO getResumeById(Integer id) {
        Resume resume = resumMapper.getResumeById(id);
        //将Resume对象转换成ResumeVo对象
        ResumeVO resumeVo = generateResumeVo(resume);
        return resumeVo;
    }

    /**
     * 询问ai查询简历
     *
     * @param query
     * @return
     */
    @Override
    public List<ResumeVO> getAiResume(AIResumeQuery query) {
        // 查询用户关联的公司id
        if (query.getUserId() == null){
            return List.of();
        }
        Integer companyId = userMapper.selectCompanyId(query.getUserId());
        if (companyId == null) {
            return List.of();
        }
        query.setCompanyId(companyId);
        List<Resume> resumeList = resumMapper.getAiResume(query);
        if (resumeList != null && resumeList.size() > 0) {
            return resumeList.stream().map(this::generateResumeVo).toList();
        }
        return List.of();
    }

    /**
     * 构建Resume对象
     * @param resumeDto
     * @return
     */
    private Resume generateResume(ResumeDto resumeDto) {
        Resume resume = new Resume();
        resume.setName(resumeDto.getName());
        resume.setGender(resumeDto.getGender());
        resume.setBirthDate(resumeDto.getBirthDate());
        resume.setPhone(resumeDto.getPhone());
        resume.setEmail(resumeDto.getEmail());
        resume.setAddress(resumeDto.getAddress());
        resume.setJobIntention(resumeDto.getJobIntention());
        resume.setSelfIntroduction(resumeDto.getSelfIntroduction());
        resume.setUpdateTime(LocalDateTime.now());
        //将educationDto、workExperienceDto、projectDto、skills转换成JSON字符串保存在数据库中
        resume.setEducation(JSONUtil.toJsonStr(resumeDto.getEducation()));
        resume.setWorkExperience(JSONUtil.toJsonStr(resumeDto.getWorkExperience()));
        resume.setProjects(JSONUtil.toJsonStr(resumeDto.getProjects()));
        resume.setSkills(JSONUtil.toJsonStr(resumeDto.getSkills()));
        return resume;
    }

    /**
     * 构建ResumeVo对象
     * @param resume
     * @return
     */
    private ResumeVO generateResumeVo(Resume resume) {
        ResumeVO resumeVo = new ResumeVO();
        resumeVo.setId(resume.getId());
        resumeVo.setUserId(resume.getUserId());
        resumeVo.setName(resume.getName());
        resumeVo.setGender(resume.getGender());
        resumeVo.setBirthDate(resume.getBirthDate());
        resumeVo.setPhone(resume.getPhone());
        resumeVo.setEmail(resume.getEmail());
        resumeVo.setAddress(resume.getAddress());
        resumeVo.setJobIntention(resume.getJobIntention());
        resumeVo.setSelfIntroduction(resume.getSelfIntroduction());
        resumeVo.setEducation(JSONUtil.toList(resume.getEducation(), ResumeVO.EducationDto.class));
        resumeVo.setWorkExperience(JSONUtil.toList(resume.getWorkExperience(), ResumeVO.WorkExperienceDto.class));
        resumeVo.setProjects(JSONUtil.toList(resume.getProjects(), ResumeVO.ProjectDto.class));
        resumeVo.setSkills(JSONUtil.toList(resume.getSkills(), String.class));
        return resumeVo;
    }
}
